<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="autocomplete.js"></script>
<script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="chrome_ex_oauth.js"></script>
<script type="text/javascript" src="zoqui.js"></script>
<script>
/*
// Debug purposes:
 chrome-extension://ghjigncagcllafkekjpdcdgpfakabejh/background.html
 chrome-extension://ghjigncagcllafkekjpdcdgpfakabejh/popup.html
 chrome-extension://ghjigncagcllafkekjpdcdgpfakabejh/options.html
 chrome-extension://ghjigncagcllafkekjpdcdgpfakabejh/debug.html
*/
var concal_enabled = false;
var json_contacts = null;
var text_contacts = null;

var json_groups = null;
var text_groups = null;

var target_tabid = null;
window.testUrl = "";

var calendarUpdaterId = "mhgfpaipjaplojocdcilmpngcmbngejo";
var calendarUpdaterPort = null;

var settings = {
    nwords: 2,
    eventduration: 60,
    selectedgroup: 'ALL',
    selectedcalendar: 'ALL',
    domain: ''
};



function trim(string)
{
    return string.replace(/^\s+|\s+$/g, '');
};

function properCase(s)
{
  return s.toLowerCase().replace(/^(.)|\s(.)/g,function($1) { 
    return $1.toUpperCase(); 
  });
}
// This function is not supported yet.
function setPopup(uri){
    if (chrome.pageAction.setPopup)
        chrome.pageAction.setPopup({popup:uri});
}

var oauth = ChromeExOAuth.initBackgroundPage({
    'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken',
    'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken',
    'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken',
    'consumer_key' : 'anonymous',
    'consumer_secret' : 'anonymous',
    'scope' : 'https://www.google.com/m8/feeds/',
    'app_name' : 'ConCal - Google Chrome Extension'
});

function enable(tabId, callback){
    chrome.tabs.sendRequest(tabId, {action: 'enable', calendarId: localStorage['selectedcalendar']}, function(ret){
        if (ret){
            concal_enabled=true;
            chrome.pageAction.setIcon({tabId: tabId, path: 'enabled.png'});
            updateSettings();
            if (callback && typeof(callback)=='function'){
                callback(tabId);
            }
        }
    });    
};

function disable(tabId, callback){
    chrome.tabs.sendRequest(tabId, { action: 'disable'}, function(ret){
        if (ret){
            concal_enabled=false;
            chrome.pageAction.setIcon({tabId: tabId, path: 'on.png'});
            if (callback && typeof(callback)=='function'){
                callback(tabId);
            }
        }
    });   
};

function toggle(callback)
{
    chrome.tabs.getSelected(null, function(tab) {
        callback(tab.id);
    });
};

function login(tabId)
{
    try{        
        chrome.tabs.getAllInWindow(null, function(all) {
            chrome.tabs.getSelected(null, function(tab) {
                chrome.tabs.move(tab.id, {index : all.length-1}, function(){
                    oauth.authorize(function(){
                        loadAll(tabId);
                    });                
                });
            });
        });    
    }
    catch(err){
        if (confirm('Authorization token could not be validated\nWould you like to erase stored tokens?')){
            logout(tabId);
        }
    }
};

function logout(tabId){
    disable(tabId, function(tabId){
        oauth.clearTokens();
        json_contacts=null;
        json_groups=null;
        chrome.pageAction.setIcon({tabId: tabId, path: 'off.png'});    
    });
};

function updateSettings()
{   
    settings.nwords           =  localStorage["nwords"];
    settings.eventduration    =  localStorage["eventduration"];
    settings.selectedgroup    =  localStorage['selectedgroup'];
    settings.selectedcalendar =  localStorage['selectedcalendar'];
    settings.domain           =  localStorage['domain'];
    
    if (!settings.nwords)
        settings.nwords=2;
    
    if (!settings.eventduration)
        settings.eventduration=60;
    
    if (!settings.selectedgroup)
        settings.selectedgroup='ALL';
    
    if (!settings.selectedcalendar)
        settings.selectedcalendar='ALL';   
    
    if (settings.eventduration!=60){
        if(settings.nwords>2)
            settings.nwords=2;
    }
    
    if (!settings.domain)
        settings.domain='';
        
    if (target_tabid){
        chrome.tabs.sendRequest(target_tabid,{action:'updateSettings', data: settings},function(ret){
            settings = ret;
        });
    }
};


function filter(startwithstr){
    var items = [];
    console.log("filtering");
    if (json_contacts && json_contacts['feed'] && json_contacts.feed['entry']){
        var entry = null;
        var pattern = new RegExp('\\b'+startwithstr,"i");
        for (var i = 0; i<json_contacts.feed.entry.length; i++) {
            entry = json_contacts.feed.entry[i];
            var id = entry['id'];
			var name = entry['title']['$t'];		
			var groupOK=true;
			if (settings.selectedgroup && settings.selectedgroup!='ALL' && entry['gContact$groupMembershipInfo']){
				for(var igroup=0;(!groupOK && igroup<entry['gContact$groupMembershipInfo'].length);igroup++){
					groupOK=(settings.selectedgroup==entry['gContact$groupMembershipInfo'][igroup]['href']);
				}
			}
            if (name.search(pattern)>=0 && groupOK){
                name = properCase(name);
                var autosugestItem = {
					'id'    : id,
                    'info'  : '',
                    'value' : name,
					'seq'   : i
                };
                var phones = '';
                if (entry['gd$phoneNumber']){
                    for(var iphone=0;iphone<entry['gd$phoneNumber'].length;iphone++){
                        var phone = entry['gd$phoneNumber'][iphone]['$t'];
                        if (trim(phone)!==''){
                            phones = phones + '[' + phone + '] ';
                        }
                    }
                    autosugestItem.info = phones;
                }
                else{
                    autosugestItem.info = name;
                }
                items.push(autosugestItem);
            }        
        }
        items.sort(function(a,b){
            return (a.value==b.value)?0:(a.value>b.value?1:-1);
        });
    }
    console.log(items.length);
    return { 'results': items };
};

function getGroups(){
    var groups = [];
    groups.push({'id':'ALL','name':'ALL'});
    if (json_groups && json_groups['feed'] && json_groups.feed['entry']){
        var entry = null;
        for (var i = 0; i<json_groups.feed.entry.length; i++) {
            entry = json_groups.feed.entry[i];
            var id = entry['id']['$t'];
            var name = entry['title']['$t'];
            var group = {
                'id' : id,
                'name' : name
            };
            groups.push(group);
        }
        groups.sort(function(a,b){
            return (a.name==b.name)?0:(a.name>b.name?1:-1);
        });
    }
    return groups;
}

function loadGroups(tabId){
    var urlgrp = "https://www.google.com/m8/feeds/groups/default/full";   
    oauth.sendSignedRequest(
        urlgrp, 
        function(text,xhr){
            try{
                text_groups= text;
                json_groups = eval('('+text+')');                
            }
            catch(err){
                text_groups = null;
                json_groups = null;
            }
        },
        {'parameters' : {'alt' : 'json', 'max-results' : 100}}
    );

}

function loadContacts(tabId){
    var url = "https://www.google.com/m8/feeds/contacts/default/full";
    var par = {'parameters' : null };
    if (settings.selectedgroup==='ALL'){
        par.parameters = {'alt' : 'json', 'max-results' : 9999}
    }
    else{
        par.parameters = {'alt' : 'json', 'max-results' : 9999, 'group' : settings.selectedgroup }
    }
    oauth.sendSignedRequest(
        url, 
        function(text,xhr){
            try{
                //json_contacts = JSON.parse(text);
                text_contacts = text;
                json_contacts = eval('('+text+')');
                chrome.pageAction.setIcon({tabId: tabId, path: concal_enabled?'enabled.png':'on.png'});
                if (!concal_enabled)
                    enable(tabId);
            }
            catch(err){
                logout(tabId);
                json_contacts = null;
                text_contacts = null;
                chrome.pageAction.setIcon({tabId: tabId, path: concal_enabled?'enabled.png':'off.png'});
            }
        },
        par
    );
};

function loadAll(tabId){
    chrome.pageAction.setIcon({tabId: target_tabid, path: 'reload.png'});
    loadGroups(tabId);
    loadContacts(tabId);
    if (!target_tabid){
        target_tabid=tabId;
    }
    updateSettings();
}

function reload(){
    if (target_tabid){
        chrome.pageAction.setIcon({tabId: target_tabid, path: 'reload.png'});
        loadAll(target_tabid);
    }
}

function show_options() {
  chrome.tabs.getSelected(null, function(tab) {
    if (window.testUrl == "") {
      window.testUrl = tab.url;
    }
    var tabs = chrome.extension.getExtensionTabs();
    if (tabs && tabs.length) {
      var optionsUrl = chrome.extension.getURL("options.html");
      chrome.tabs.getAllInWindow(null, function(all) {
        for (var i = 0; i < all.length; i++) {
          if (all[i].url == optionsUrl) {
            chrome.tabs.update(all[i].id, {selected: true });
            return;
          }
        }
      });
    } else {
      chrome.tabs.create({"url":"options.html"});
    }
  });
}

function open_contacts() {
    chrome.tabs.getSelected(null, function(tab) {
        var targeturl="http://www.google.com/contacts";
        if (settings.domain!==''){
            var parts = settings.domain.split('@');
            var domain = parts.length>0?parts[1]:'';
            if (domain && domain.length){
                targeturl = targeturl + '/a/' + domain;
            }
        }
        chrome.tabs.getAllInWindow(null, function(all) {
            for (var i = 0; i < all.length; i++) {
                if (all[i].url.search(('^'+targeturl))>=0){           
                //if (all[i].url == targeturl) {
                    chrome.tabs.update(all[i].id, {selected: true });
                    return;
                }
            }
            chrome.tabs.create({"url":targeturl});
        });        
    });
}

//-------------------------------------------------------------------
function init() {
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        if (tab.url.match(/^(http|https)\:\/\/www.google.com\/calendar/i)) {
            target_tabid = tabId;
            chrome.pageAction.show(tabId);
            var hasToken = oauth.hasToken();
            if (hasToken){
                if (json_contacts && json_groups){
                    updateSettings();
                    concal_enabled ? enable(tabId) : disable(tabId); // If the tab was closed, check its last status
                    return;
                }
                else{
                    loadAll(tabId);
                }
            }            
        }
    });
    
    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
        if (request.action == "searchcontacts"){
            var jsondata = filter(request.startwithstr);
            sendResponse({status:'OK',data: jsondata}); 
        }
        else if (request.action == 'onCreateClicked'){
            localStorage['selectedcalendar'] = request.calendarId; // save the selected calendar
			// try to stabilish the first connection to the ex
			if (calendarUpdaterPort==null){
				try{
					console.log("Concal is now trying to connect calendarUpdaterPort");
					calendarUpdaterPort = chrome.extension.connect(calendarUpdaterId, {name: "updater"});
					console.log("Concal is now connected to calendarUpdaterPort");
					calendarUpdaterPort.onMessage.addListener(function(ret) {
						if (ret.action == "writeevent"){
							console.log('calendarUpdaterPort replied with: ' + ret.status + ' ' + ret.msg);
						};
						return;
					});
				}
				catch(e){
					calendarUpdaterPort = null;
					console.log("Concal could not to calendarUpdaterPort");
				}
			}
			if (calendarUpdaterPort!=null){
				console.log('sending message to calendar updater');
				var msg = {
					action: "writeevent", 
					calendarId: request.calendarId, 
					calendarTitle: request.calendarTitle ,
					eventTitle: request.eventTitle
				};
				calendarUpdaterPort.postMessage(msg);
				return;
			}
			sendResponse({status:'OK',data: request.calendarId}); 
        }
        else{
            sendResponse({}); 
        }
    });
	
	// The ID of the extension we want to talk to.
	
	// Make a simple request:
	/*
	var calendarUpdaterId = "mhgfpaipjaplojocdcilmpngcmbngejo";
	chrome.extension.sendRequest(
		calendarUpdaterId, 
		{getTargetData: true},
		function(response) {
			if (targetInRange(response.targetData)){
				chrome.extension.sendRequest(calendarUpdaterId, {activateLasers: true});
			}
		}
	);


	// Start a long-running conversation:
	try{
		calendarUpdaterPort = chrome.extension.connectExternal(calendarUpdaterId);
		console.log("Concal is now connected to calendarUpdaterPort");
		port.onMessage.addListener(function(msg) {
			if (msg.action == "writeevent"){
				console.log('Concal writeevent status: ' + msg.status);
			};
		});
	}
	catch(e){
		calendarUpdaterPort = null;
		console.log("Concal could not to calendarUpdaterPort");
	}        
	*/
}
init();
</script>

